// This file is part of Background Music.
//
// Background Music is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 2 of the
// License, or (at your option) any later version.
//
// Background Music is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Background Music. If not, see <http://www.gnu.org/licenses/>.

//
//  BGMHermes.m
//  BGMApp
//
//  Copyright © 2016-2018 Kyle Neideck
//

// Self Include
#import "BGMHermes.h"

// Auto-generated Scripting Bridge header
#import "Hermes.h"

// Local Includes
#import "BGMScriptingBridge.h"

// PublicUtility Includes
#import "CADebugMacros.h"


#pragma clang assume_nonnull begin

@implementation BGMHermes {
    BGMScriptingBridge* scriptingBridge;
}

- (instancetype) init {
    // If you're copying this class, replace the ID string with a new one generated by uuidgen. (Command line tool.)
    if ((self = [super initWithMusicPlayerID:[BGMMusicPlayerBase makeID:@"0CDC67B0-56D3-4D94-BC06-6E380D8F5E34"]
                                        name:@"Hermes"
                                    bundleID:@"com.alexcrichton.Hermes"])) {
        scriptingBridge = [[BGMScriptingBridge alloc] initWithMusicPlayer:self];
    }
    
    return self;
}

- (HermesApplication* __nullable) hermes {
    return (HermesApplication* __nullable)scriptingBridge.application;
}

- (void) wasSelected {
    [super wasSelected];
    [scriptingBridge ensurePermission];
}

- (BOOL) isRunning {
    // Note that this will return NO if is self.hermes is nil (i.e. Hermes isn't running).
    return self.hermes.running;
}

// isPlaying and isPaused check self.running first just in case Hermes is closed but self.hermes hasn't become
// nil yet. In that case, reading self.hermes.playerState could make Scripting Bridge open Hermes.

- (BOOL) isPlaying {
    return self.running && (self.hermes.playbackState == HermesPlayerStatesPlaying);
}

- (BOOL) isPaused {
    return self.running && (self.hermes.playbackState == HermesPlayerStatesPaused);
}

- (BOOL) pause {
    // isPlaying checks isRunning, so we don't need to check it here and waste an Apple event
    BOOL wasPlaying = self.playing;
    
    if (wasPlaying) {
        DebugMsg("BGMHermes::pause: Pausing Hermes");
        [self.hermes pause];
    }
    
    return wasPlaying;
}

- (BOOL) unpause {
    // isPaused checks isRunning, so we don't need to check it here and waste an Apple event
    BOOL wasPaused = self.paused;
    
    if (wasPaused) {
        DebugMsg("BGMHermes::unpause: Unpausing Hermes");
        [self.hermes play];
    }
    
    return wasPaused;
}

@end

#pragma clang assume_nonnull end

